package org.changs.launcher.device;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;

import org.changs.aplug.interf.Action1;
import org.changs.aplug.used.NetworkReceiver;
import org.changs.aplug.utils.NetworkUtils;
import org.changs.aplug.utils.WifiUtils;

import java.util.List;

import javax.inject.Inject;

import timber.log.Timber;

/**
 * Created by yincs on 2017/9/15.
 */

public class ConnectWifiOpt extends NetworkReceiver implements Runnable {
    private final WifiManager mWifiManager;
    private final Context mContext;
    private final Handler mHandler;
    private Action1<Boolean> mConnectedAction;
    private String mBssid;

    @Inject
    public ConnectWifiOpt(WifiManager mWifiManager, Context mContext, Handler mHandler) {
        this.mWifiManager = mWifiManager;
        this.mContext = mContext;
        this.mHandler = mHandler;
    }


    public String getSSID() {
        return DeviceConnectUtils.getApWifiSSID(mContext);
    }

    public String getPwd() {
        return DeviceConnectUtils.getApWifiPwd(mContext);
    }


    @Override
    protected void onWifiState(int wifiState) {
        if (wifiState == WifiManager.WIFI_STATE_DISABLED) {
            //手动关掉了
        } else if (wifiState == WifiManager.WIFI_STATE_ENABLED) {//已经打开
            run();
        }
    }

    @Override
    protected void onConnected(int networkType) {
        super.onConnected(networkType);
        if (networkType == NetworkUtils.NETWORK_WIFI) {
            run();
        }
    }

    @Override
    protected void onDisConnected() {
        super.onDisConnected();
        mWifiManager.startScan();
        if (mConnectedAction != null) mConnectedAction.call(false);
    }

    @Override
    public void run() {
        mHandler.removeCallbacks(this);
        if (mWifiManager.getWifiState() != WifiManager.WIFI_STATE_ENABLED) {
            if (WifiUtils.isWifiApEnabled(mWifiManager)) {
                WifiUtils.closeWifiAp(mWifiManager);
            } else {
                boolean wifiEnabled = mWifiManager.setWifiEnabled(true);
                Timber.d("wifiEnabled = " + wifiEnabled);
            }
            mHandler.postDelayed(this, 5000);
        } else {
            final WifiInfo connectionInfo = mWifiManager.getConnectionInfo();
            Timber.d("connectionInfo.getSSID() = " + connectionInfo.getSSID());
            final String ssid = getSSID();
            Timber.d("SSID = " + ssid);
            String bssid = connectionInfo.getBSSID();
            Timber.d("BSSID = " + bssid);
            final String pwd = getPwd();
            Timber.d("pwd = " + pwd);
            if (WifiUtils.isWifiConnected(mContext) &&
                    (connectionInfo.getSSID().contains(ssid)
                            || bssid.equals(mBssid))) {
                //已经连接
                if (mConnectedAction != null) mConnectedAction.call(true);
            } else {
                final List<ScanResult> scanResults = mWifiManager.getScanResults();
                Timber.d("scanResults.size() = " + scanResults.size());
                ScanResult legalScanResult = null;
                for (ScanResult scanResult : scanResults) {
//                    Timber.d("scanResult.SSID = " + scanResult.SSID);
//                    Timber.d("scanResult.BSSID = " + scanResult.BSSID);
                    if (scanResult.SSID.equals(ssid)) {
                        legalScanResult = scanResult;
                        break;
                    }
                }
                Timber.d("legalScanResult = " + legalScanResult);
                if (legalScanResult == null) {
                    final boolean startScan = mWifiManager.startScan();
                    Timber.d("startScan = " + startScan);
                    mHandler.postDelayed(this, 2000);
                } else {
                    mBssid = legalScanResult.BSSID;
                    Timber.d("mBssid = " + mBssid);
                    mWifiManager.disconnect();
                    WifiUtils.removeNetWorkAll(mWifiManager);
                    int addNetwork = WifiUtils.addNetwork(mWifiManager, ssid, pwd, WifiUtils.WIFICIPHER_WPA);
                    Timber.d("addNetwork = " + addNetwork);
                    if (addNetwork != -1) {
                        final boolean enableNetwork = mWifiManager.enableNetwork(addNetwork, true);
                        Timber.d("enableNetwork = " + enableNetwork);
                        if (enableNetwork) {
                            boolean reassociate = mWifiManager.reassociate();
                            Timber.d("reassociate = " + reassociate);
                            if (reassociate) {
                                mHandler.postDelayed(this, 8888);
                                return;
                            }
                        }
                    }
                    mHandler.postDelayed(this, 1000);
                }
            }
        }
    }

    public void setConnectedAction(Action1<Boolean> action) {
        this.mConnectedAction = action;
    }
}